package com.anjubao.parking.municipal.parkinglot.controller;

import com.anjubao.parking.municipal.common.dto.ApiCode;
import com.anjubao.parking.municipal.common.dto.ApiResult;
import com.anjubao.parking.municipal.common.utils.BeanUtils;
import com.anjubao.parking.municipal.common.utils.MunicipalParkingUtils;
import com.anjubao.parking.municipal.parkinglot.dto.VideoPileDto;
import com.anjubao.parking.municipal.parkinglot.dto.VideoPileReturnCodeDto;
import com.anjubao.parking.municipal.parkinglot.form.*;
import com.anjubao.parking.municipal.parkinglot.model.ParkingLotDeviceVideoPile;
import com.anjubao.parking.municipal.parkinglot.model.ParkingLotDeviceVideoPileSlot;
import com.anjubao.parking.municipal.parkinglot.service.ParkingLotDeviceVideoPileService;
import com.anjubao.parking.municipal.parkinglot.service.ParkingLotDeviceVideoPileSlotService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;


/**
 * 视频桩基本信息API
 *
 * @author zhangyunbo
 */
@RestController
@RequestMapping("/parking-lots-device-videopiles")
@Api(value = "ParkingLotDeviceVideoPile模块", tags = {"视频桩管理接口"})
public class ParkingLotDeviceVideoPileController {
    private static final Logger logger = LoggerFactory.getLogger(ParkingLotDeviceVideoPileController.class);
    @Autowired
    private ParkingLotDeviceVideoPileService parkingLotDeviceVideoPileService;


    @Autowired
    private ParkingLotDeviceVideoPileSlotService parkingLotDeviceVideoPileSlotService;


    /**
     * 新增视频桩
     *
     * @param form
     * @return
     */
    @PostMapping(value = "")
    @ApiOperation(value = "新增视频桩", notes = "", code = 2000)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "form", required = true, dataType = "VideoPileAddForm", paramType = "body")
    })
    @ApiResponses(value = {
            @ApiResponse(code = 5000, message = "操作失败"),
    })
    public ApiResult<VideoPileReturnCodeDto> createVideoPile(@RequestBody @Valid VideoPileAddForm form) {
        logger.info("新增视频桩 {} ", form);
        ParkingLotDeviceVideoPile entityCreated = parkingLotDeviceVideoPileService.saveVideoPile(BeanUtils.transform(ParkingLotDeviceVideoPile.class, form), null);
        List<ParkingLotDeviceVideoPileSlot> videoPileSlots = new ArrayList<>();
        //新增视频桩后添加泊位信息
        for (int i = 0; form.getSlotCodes() != null && i < form.getSlotCodes().size(); i++) {
            videoPileSlots.add(new ParkingLotDeviceVideoPileSlot()
                    .setParkingLotDeviceVideoPileId(entityCreated.getId()).setParkingLotSlotId(MunicipalParkingUtils.getIdByCode(form.getSlotCodes().get(i))));

        }
        parkingLotDeviceVideoPileSlotService.saveVideoPileSlot(videoPileSlots);
        parkingLotDeviceVideoPileService.syncVideoPile(entityCreated,videoPileSlots);
        return ApiResult.success(new VideoPileReturnCodeDto().setVideoPileCode(entityCreated.getCode()));
    }


    @PutMapping("/{videoPileCode}")
    @ApiOperation(value = "修改视频桩信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "form", required = true, dataType = "VideoPileEditForm", paramType = "body"),
            @ApiImplicitParam(name = "videoPileCode", value = "视频桩code", required = true, dataType = "String", paramType = "path")
    })
    @ApiResponses(value = {
            @ApiResponse(code = 5000, message = "操作失败"),
    })
    /**
     * 更新
     *
     * @param parkingLotCode
     * @param form
     * @return
     */
    public ApiResult<VideoPileReturnCodeDto> updateVideoPile(@PathVariable String videoPileCode, @RequestBody @Valid VideoPileEditForm form) {
        logger.info("修改视频桩信息 {} ", form);
        ParkingLotDeviceVideoPile videoPile = BeanUtils.transform(ParkingLotDeviceVideoPile.class, form);
        videoPile.setCode(videoPileCode);
        List<ParkingLotDeviceVideoPileSlot> videoPileSlots = new ArrayList<>();
        for (int i = 0; i < form.getSlotCodes().size(); i++) {
            videoPileSlots.add(new ParkingLotDeviceVideoPileSlot().setParkingLotDeviceVideoPileId(MunicipalParkingUtils.getIdByCode(videoPile.getCode()))
                    .setParkingLotSlotId(MunicipalParkingUtils.getIdByCode(form.getSlotCodes().get(i))));
        }
        ParkingLotDeviceVideoPile updated = parkingLotDeviceVideoPileService.saveVideoPile(videoPile, videoPileSlots);
        //同步视频桩
        parkingLotDeviceVideoPileService.syncVideoPile(updated,videoPileSlots);
        return ApiResult.success(new VideoPileReturnCodeDto().setVideoPileCode(updated.getCode()));
    }

    @GetMapping("")
    @ApiOperation(value = "查询视频桩信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "videoPileStatus", value = "视频桩在线状态(1:在线，0:断线)", dataType = "int", paramType = "query", allowableValues = "1,0", type = "integer")
    })
    @ApiResponses(value = {
            @ApiResponse(code = 5000, message = "操作失败"),
    })
    /**
     * 查询
     *
     * @param form
     * @return
     */
    public ApiResult<List<VideoPileDto>> getVideoPile(VideoPileQueryForm form) {
        if (form.getCityId() == null && form.getDistrictId() == null && form.getProvinceId() == null) {
            return new ApiResult<>(ApiCode.STATUS_INTERNAL_ERROR.getCode(), "省市区ID不允许同时为空");
        }
        logger.info("查询视频桩信息 {}", form);
        Page<VideoPileDto> page = new Page<>();
        page.setSize(form.getPageSize());
        page.setCurrent(form.getPage());
        Page<VideoPileDto> videoPileLists = parkingLotDeviceVideoPileService.getVideoPiles(page, form);
        return ApiResult.success(videoPileLists.getRecords(), (int) videoPileLists.getTotal());
    }

    @GetMapping("/{videoPileCode}")
    @ApiOperation(value = "查看单个视频桩接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "videoPileCode", value = "视频桩code", required = true, dataType = "String", paramType = "path")
    })
    @ApiResponses(value = {
            @ApiResponse(code = 5000, message = "操作失败"),
    })
    /**
     * 查询
     *
     * @param videoPileCode    视频桩编号
     * @return
     */
    public ApiResult<VideoPileDto> getVideoPile(@PathVariable String videoPileCode) {
        logger.info("获取单个视频桩 {}", videoPileCode);
        VideoPileDto videoPileDto = parkingLotDeviceVideoPileService.getVideoPileDto(MunicipalParkingUtils.getIdByCode(videoPileCode));
        return ApiResult.success(videoPileDto);
    }


    @GetMapping("/status/{videoPileCode}")
    @ApiOperation(value = "修改视频桩状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "videoPileCode", value = "视频桩code", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "onlineStatus", value = "在线状态 0断线 1在线", dataType = "String")
    })
    @ApiResponses(value = {
            @ApiResponse(code = 5000, message = "操作失败"),
    })
    /**
     * 查询
     *
     * @param videoPileCode    视频桩编号
     * @return
     */
    public ApiResult updateStatus(@PathVariable String videoPileCode, String onlineStatus) {
        logger.info("修改视频桩状态 {}", videoPileCode);
        parkingLotDeviceVideoPileService.updateStatus(onlineStatus, videoPileCode);
//        VideoPileDto videoPileDto = parkingLotDeviceVideoPileService.getVideoPileDto(MunicipalParkingUtils.getIdByCode(videoPileCode));
        return ApiResult.success();
    }

    @ApiOperation("删除视频桩接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "videoPileCode", value = "视频桩code", required = true, dataType = "string", paramType = "path")
    })
    @DeleteMapping("/{videoPileCode}")
    public ApiResult deleteVideoPile(@PathVariable String videoPileCode) {
        parkingLotDeviceVideoPileService.deleteVideoPile(MunicipalParkingUtils.getIdByCode(videoPileCode));
        parkingLotDeviceVideoPileService.syncDelete(videoPileCode);
        return ApiResult.success();
    }


}
